package com.alog.storage.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import com.alog.storage.domain.ViewHolder;
import java.util.ArrayList;
import java.util.List;

/**
 * adapter基类, 供各adapter继承
 */
public abstract class BaseAdapter<T> extends android.widget.BaseAdapter {
    protected Context mContext;
    protected int mLayoutId;
    public List<T> dataList = new ArrayList<>();

    public BaseAdapter(Context context, int layoutId, List<T> dataList) {
        this.mContext = context;
        this.mLayoutId = layoutId;
        this.dataList = dataList;
    }

    @Override
    public int getCount() {
        if (dataList != null) {
            return dataList.size();
        }
        return 0;
    }

    @Override
    public T getItem(int position) {
        if (dataList != null && dataList.size() > position) {
            return dataList.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = ViewHolder.get(mContext, convertView, parent, mLayoutId, position);
        setDataToView(viewHolder, getItem(position));
        return viewHolder.getConvertView();
    }

    /**
     * 子adapter实现此方法设置需要显示的数据到控件上
     *
     * @param viewHolder 控件引用缓存
     * @param item       实体数据类
     */
    public abstract void setDataToView(ViewHolder viewHolder, T item);

    public void onDestroy() {
        mContext = null;
        mLayoutId = 0;
        if (dataList != null) {
            dataList.clear();
            dataList = null;
        }
    }

}
